package com.supor.aiot.food.ui.food;

import android.annotation.SuppressLint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject;
import com.alipay.mobile.common.utils.StringUtils;
import com.android.baseconfig.base.BaseActivity;
import com.android.baseconfig.base.BasePresenter;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.views.CircleImageView;
import com.android.baseconfig.common.views.CustomTitleBar;
import com.bumptech.glide.Glide;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporApplication;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.ui.view.DotTextView;
import com.supor.aiot.common.utils.MarketUtils;
import com.supor.aiot.food.R;
import com.supor.aiot.food.adapter.CookerProductorAdapter;
import com.supor.aiot.food.adapter.FlexTextAdapter;
import com.supor.aiot.food.api.SearchFoodImpl;
import com.supor.aiot.food.bean.ChefDetailBean;
import com.supor.aiot.food.bean.RecipeHotBean;
import com.supor.aiot.food.bean.RequstChefBean;
import com.supor.aiot.food.utils.DoubleClickUtils;
import com.supor.aiot.food.view.DampView;
import com.supor.aiot.food.view.ShareDialog;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

@Route(path = PathUrl.PATH_COOKER_HOME)
public class CookerHomeActivity extends BaseActivity {

    RelativeLayout rlTitleBack;
    RelativeLayout llRequestUpdate;
    RelativeLayout rlCookerHeader;
    ImageView ivCookerBg;
    TextView tvCookerName;
    TextView tvCookerDesc;
    LinearLayout llAuthorTag;
    TextView tvRenqiSize;
    TextView tvProductionSize;
    TextView tvLikeSize;
    CircleImageView ivCookerAvatar;
    RecyclerView rvCookerMark;
    DotTextView tvCookerHot;
    DotTextView tvCookerNew;
    ImageView ivFriendMatrix;
    ImageView ivWechat;
    SwipeRecyclerView rvCookerProduction;
    DampView food;
    SmartRefreshLayout refreshLayout;
    CustomTitleBar customTitleBar;
    RelativeLayout rlButtonButtom;
    RelativeLayout rlButtonHead;
    DotTextView tvHeadHot;
    DotTextView tvHeadNew;
    TextView noneResult;

    private List<String> mList = new ArrayList<>();
    private List<RecipeHotBean> mHotList;
    private String chefID;
    private FlexTextAdapter textAdapter;
    private CookerProductorAdapter hotAdapter;
    private static final String CHEF_ID = "CHEF_ID";
    private ChefDetailBean chefDetailBean;
    private boolean originState;
    private int originPage = 1;
    private ShareDialog shareDialog;
    private LinearLayout llSkeleton;

    @Override
    protected int resourceId() {
        return R.layout.activity_cooker_home;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initData() {
        super.initData();
        initClassifyData();
        initRecycleView();
        initListener();
    }

    private void initListener() {
        rlTitleBack.setOnClickListener(view -> CookerHomeActivity.this.finish());
        tvCookerHot.setOnClickListener(view -> {
            originState = false;
            changeState(originState);
        });
        tvHeadHot.setOnClickListener(view -> {
            originState = false;
            changeState(originState);
        });
        tvCookerNew.setOnClickListener(view -> {
            originState = true;
            changeState(originState);
        });
        tvHeadNew.setOnClickListener(view -> {
            originState = true;
            changeState(originState);
        });

        llRequestUpdate.setOnClickListener(view -> {
            if (AppAgent.isLogin() && null != GlobalDataCache.userInfo) {
                RequstChefBean bean = new RequstChefBean();
                bean.setWantType("CHEF");
                if (!TextUtils.isEmpty(chefID)) {
                    bean.setAddrId(chefID);
                    requestUpdate(bean);
                } else {
                    ToastUtils.getInstance().showCustomToast(R.string.check_error);
                }
            } else {
                AppAgent.showLogin(true);
            }
        });

        ivFriendMatrix.setOnClickListener(view -> {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            String share = AppAgent.getChefShareUrl() + chefID;
            initShare(share, 2);
        });

        ivWechat.setOnClickListener(view1 -> {
            if (DoubleClickUtils.isFastDoubleClick()) return;
            String share = AppAgent.getChefShareUrl() + chefID;
            initShare(share, 1);
        });
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            originPage++;
            if (originState) {
                getChefNew(chefID);
            } else {
                getChefGood(chefID);
            }
        });
        refreshLayout.setRefreshFooter(new ClassicsFooter(CookerHomeActivity.this));
        customTitleBar.setIvLeftOnClickListener(view -> {
            CookerHomeActivity.this.finish();
        });
    }

    private void showShare() {
        String share = AppAgent.getChefShareUrl() + chefID;
        ShareDialog.Builder builder = new ShareDialog.Builder(this);
        builder.setFriendListener(view -> {
            initShare(share, 2);
            shareDialog.dismiss();
        });
        builder.setWechatListener(view -> {
            initShare(share, 1);
            shareDialog.dismiss();
        });
        builder.setShadow(true);
        builder.setCanCancel(true);

        shareDialog = builder.create();
        shareDialog.show();
    }


    private void initShare(String shareUrl, int shareType) {
        if (!TextUtils.isEmpty(shareUrl)) {
            // // 分享类型：0取消分享；1微信；2微信朋友圈；3 QQ好友；4 QQ空间；5微博；6支付宝；7抖音
            // jo.put(Constants.Key.param_shareType, 1);
            // // 分享方式：0x1-text，0x2-image，0x3-URL
            // jo.put(Constants.Key.param_type, 3);
            JSONObject jo = new JSONObject();
            jo.put(Constants.Key.param_shareType, shareType);
            jo.put(Constants.Key.param_title, TextUtils.isEmpty(chefDetailBean.getChefTitle()) ? getResources().getString(R.string.share_title) : chefDetailBean.getChefTitle());
            jo.put(Constants.Key.param_desc, chefDetailBean.getChefText());
            jo.put(Constants.Key.param_type, 3);
            jo.put(Constants.Key.param_tinyAppShare, 0);
            jo.put(Constants.Key.param_path, shareUrl);
            SuporPresenter.getInstance().sendShareMsg(jo);
        } else {
            ToastUtils.getInstance().showCustomToast(R.string.check_error);
        }
    }

    private void changeState(boolean origin) {
        originPage = 1;
        if (origin) {
            tvCookerHot.setTextColor(getResources().getColor(R.color.content_assist));
            tvCookerNew.setTextColor(getResources().getColor(R.color.content_default));
            tvCookerNew.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            tvCookerHot.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            tvCookerHot.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.sp_13));
            tvCookerNew.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.sp_16));
            tvCookerHot.setDotVisible(false);
            tvCookerNew.setDotVisible(true);

            tvHeadHot.setTextColor(getResources().getColor(R.color.content_assist));
            tvHeadNew.setTextColor(getResources().getColor(R.color.content_default));
            tvHeadNew.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            tvHeadHot.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            tvHeadHot.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.sp_13));
            tvHeadNew.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.sp_16));
            tvHeadHot.setDotVisible(false);
            tvHeadNew.setDotVisible(true);

            if (!TextUtils.isEmpty(chefID)) {
                getChefNew(chefID);
            } else {
                ToastUtils.getInstance().showCustomToast(R.string.check_error);
            }
        } else {
            tvCookerNew.setTextColor(getResources().getColor(R.color.content_assist));
            tvCookerHot.setTextColor(getResources().getColor(R.color.content_default));
            tvCookerNew.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.sp_13));
            tvCookerHot.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.sp_16));
            tvCookerNew.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            tvCookerHot.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            tvCookerHot.setDotVisible(true);
            tvCookerNew.setDotVisible(false);

            tvHeadNew.setTextColor(getResources().getColor(R.color.content_assist));
            tvHeadHot.setTextColor(getResources().getColor(R.color.content_default));
            tvHeadNew.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.sp_13));
            tvHeadHot.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.sp_16));
            tvHeadNew.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            tvHeadHot.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            tvHeadHot.setDotVisible(true);
            tvHeadNew.setDotVisible(false);

            if (!TextUtils.isEmpty(chefID)) {
                getChefGood(chefID);
            } else {
                ToastUtils.getInstance().showCustomToast(R.string.check_error);
            }
        }
    }

    @Override
    protected void initView() {
        super.initView();
        rlTitleBack = findViewById(R.id.rl_title_back);
        llRequestUpdate = findViewById(R.id.ll_request_update);
        rlCookerHeader = findViewById(R.id.rl_cooker_header);
        tvCookerName = findViewById(R.id.tv_cooker_name);
        llAuthorTag = findViewById(R.id.ll_author_tag);
        tvRenqiSize = findViewById(R.id.tv_renqi_size);
        tvProductionSize = findViewById(R.id.tv_production_size);
        tvLikeSize = findViewById(R.id.tv_like_size);
        ivCookerAvatar = findViewById(R.id.iv_cooker_avatar);
        rvCookerMark = findViewById(R.id.rv_cooker_mark);
        tvCookerHot = findViewById(R.id.tv_cooker_hot);
        tvCookerNew = findViewById(R.id.tv_cooker_new);
        ivFriendMatrix = findViewById(R.id.iv_friend_matrix);
        ivWechat = findViewById(R.id.iv_wechat);
        ivCookerBg = findViewById(R.id.iv_cooker_bg);
        rvCookerProduction = findViewById(R.id.rv_cooker_production);
        llSkeleton = findViewById(R.id.ll_skeleton);
        food = findViewById(R.id.food);

        customTitleBar = findViewById(R.id.classify_toolbar);
        tvCookerDesc = findViewById(R.id.tv_cooker_desc);
        refreshLayout = findViewById(R.id.refreshLayout);
        rlButtonHead = findViewById(R.id.rl_button_head);
        rlButtonButtom = findViewById(R.id.rl_button_buttom);
        tvHeadHot = findViewById(R.id.tv_hot_head);
        tvHeadNew = findViewById(R.id.tv_new_head);
        noneResult = findViewById(R.id.none_result);
        food.setImageView(ivCookerBg);

        refreshLayout.setEnableRefresh(false);
        food.setOnScrollChangeListener((View.OnScrollChangeListener) (view1, i, i1, i2, i3) -> {
            if (i1 > 150) {
                customTitleBar.setVisibility(View.VISIBLE);
                if (!isVisibleLocal(rlButtonButtom, true)) {
                    rlButtonHead.setVisibility(View.VISIBLE);
                } else {
                    rlButtonHead.setVisibility(View.GONE);
                }
            } else {
                customTitleBar.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 判断View是否可见
     *
     * @param target   View
     * @param judgeAll 为true时,判断View全部可见才返回true
     * @return boolean
     */
    public static boolean isVisibleLocal(View target, boolean judgeAll) {
        Rect rect = new Rect();
        target.getLocalVisibleRect(rect);
        if (judgeAll) {
            return rect.top == 0;
        } else {
            return rect.top >= 0;
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initRecycleView() {
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(this);
        layoutManager.setFlexDirection(FlexDirection.ROW);
        layoutManager.setJustifyContent(JustifyContent.FLEX_START);
        layoutManager.setFlexWrap(FlexWrap.WRAP);//按正常方向换行
        rvCookerMark.setLayoutManager(layoutManager);
        rvCookerMark.setAdapter(textAdapter);
        rvCookerMark.setLayoutManager(layoutManager);
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        rvCookerProduction.setLayoutManager(staggeredGridLayoutManager);
        rvCookerProduction.setAdapter(hotAdapter);

    }


    @SuppressLint("AutoDispose")
    private void initChefDetail(String chefID) {
        SearchFoodImpl.getInstance().getChefDetail(chefID).subscribe(result -> {
            if (result.isSuccess()) {
                chefDetailBean = result.data.rows.get(0);
                initData(chefDetailBean);
            } else {
                Log.e(TAG, "chef error");
            }

        }, throwable -> {
            Log.e(TAG, "chef查询失败: " + throwable.getMessage());
        });
    }

    /**
     * 求新菜
     *
     * @param chefID
     */
    @SuppressLint("AutoDispose")
    private void requestUpdate(RequstChefBean chefID) {
        SearchFoodImpl.getInstance().requestUpdate(chefID).subscribe(result -> {
            if (result.isSuccess()) {
                ToastUtils.getInstance().showCustomToast(R.string.request_update_success);
            } else {
                Log.e(TAG, "chef error");
            }

        }, throwable -> {
            Log.e(TAG, "chef查询失败: " + throwable.getMessage());
        });
    }


    @SuppressLint("AutoDispose")
    private void getChefNew(String chefID) {
        if (originPage == 1 && mHotList.size() == 0) {
            llSkeleton.setVisibility(View.VISIBLE);
        } else {
            llSkeleton.setVisibility(View.GONE);
        }

        SearchFoodImpl.getInstance().getCookerNew(chefID, "new", originPage, 10).subscribe(result -> {
            llSkeleton.setVisibility(View.GONE);
            if (result.isSuccess()) {
                if (originPage == 1) mHotList.clear();
                if (mHotList.size() < result.total) {
                    mHotList.addAll(result.data.rows);
                    hotAdapter.setHideTop(true);
                    hotAdapter.notifyDataSetChanged();
                }
                if (mHotList.size() == 0) {
                    noneResult.setVisibility(View.VISIBLE);
                } else {
                    noneResult.setVisibility(View.GONE);
                }
            } else {
                Log.e(TAG, "chef error");
            }
            refreshLayout.finishLoadMore();
        }, throwable -> {
            Log.e(TAG, "chef查询失败: " + throwable.getMessage());
            refreshLayout.finishLoadMore();
        });
    }

    @SuppressLint("AutoDispose")
    private void getChefGood(String chefID) {
        if (originPage == 1 && mHotList.size() == 0) {
            llSkeleton.setVisibility(View.VISIBLE);
        } else {
            llSkeleton.setVisibility(View.GONE);
        }
        SearchFoodImpl.getInstance().getCookerGood(chefID, "new", originPage, 10).subscribe(result -> {
            llSkeleton.setVisibility(View.GONE);
            if (result.isSuccess()) {
                if (originPage == 1) mHotList.clear();
                if (mHotList.size() < result.total) {
                    mHotList.addAll(result.data.rows);
                    hotAdapter.setHideTop(false);
                    hotAdapter.notifyDataSetChanged();
                }
                if (mHotList.size() == 0) {
                    noneResult.setVisibility(View.VISIBLE);
                } else {
                    noneResult.setVisibility(View.GONE);
                }
            } else {
                Log.e(TAG, "chef error");
            }
            refreshLayout.finishLoadMore();
        }, throwable -> {
            Log.e(TAG, "chef查询失败: " + throwable.getMessage());
            refreshLayout.finishLoadMore();
        });
    }


    private void initData(ChefDetailBean chefDetailBean) {
        if (!TextUtils.isEmpty(chefDetailBean.getDetailImage()))
            Glide.with(this).load(chefDetailBean.getDetailImage()).into(ivCookerAvatar);
        if (!TextUtils.isEmpty(chefDetailBean.getChefTitle())) {
            tvCookerName.setText(chefDetailBean.getChefTitle());
            customTitleBar.setTitle(chefDetailBean.getChefTitle());
        }
        if (!TextUtils.isEmpty(chefDetailBean.getChefText()))
            tvCookerDesc.setText(chefDetailBean.getChefText());
        if (!TextUtils.isEmpty(chefDetailBean.getNote()))
            Glide.with(this).load(chefDetailBean.getNote()).into(ivCookerBg);
        tvRenqiSize.setText(chefDetailBean.getWorksCount() + getResources().getString(R.string.dao));
        tvProductionSize.setText(chefDetailBean.getCookCount() + getResources().getString(R.string.count));
        tvLikeSize.setText(chefDetailBean.getLikeCount() + getResources().getString(R.string.count));
        changeState(originState);
        if (!TextUtils.isEmpty(chefDetailBean.getAdeptCuisine())) {
            mList.addAll(stringToList(chefDetailBean.getAdeptCuisine()));
            textAdapter.notifyDataSetChanged();
        }
    }

    private List<String> stringToList(String strs) {
        if (!StringUtils.isEmpty(strs)) {
            String str[] = strs.split(",");
            return Arrays.asList(str);
        } else {
            return new ArrayList<>();
        }
    }

    private void initClassifyData() {
        chefID = getIntent().getStringExtra(CHEF_ID);
        if (!TextUtils.isEmpty(chefID)) {
            initChefDetail(chefID);
        }

        if (MarketUtils.getTools().isInstalled(CookerHomeActivity.this, Constants.App.WeixinPackage)) {
            ivFriendMatrix.setVisibility(View.VISIBLE);
            ivWechat.setVisibility(View.VISIBLE);
        }

        mHotList = new ArrayList<>();

        for (int i = 0; i < 5; i++) {
            List<RecipeHotBean.MutiAvatarBean> mlist = new ArrayList<>();
            for (int j = 0; j < 3; j++) {
                mlist.add(new RecipeHotBean.MutiAvatarBean(""));
            }
        }
        textAdapter = new FlexTextAdapter(R.layout.item_flex_text, mList);
        hotAdapter = new CookerProductorAdapter(mHotList, CookerHomeActivity.this, position -> {
            RecipeHotBean bean = mHotList.get(position);
            AppAgent.startRecipePage(bean.getRecipeId(), bean.getModelId());

            SuporApplication.getInstance().mainHandler.postDelayed(()
                    -> {
                CookerHomeActivity.this.finish();
            }, 300);
        });
    }

}
